<template>
  <div style="width: 100%; display: flex; flex-direction: column; min-height: 100vh; background-color: #f5f7fa;">
    <!-- 顶部导航栏 -->
    <div
      style="display: flex; align-items: center; padding: 12px 15px; background-color: #fff; border-bottom: 1px solid #e8e8e8;">
      <!-- 左侧按钮 -->
      <el-button :class="isStart ? 'idoo-details-finish' : 'idoo-details-add'" @click="isStart ? finish() : start()"
        size="small">
        {{ isStart ? '交卷' : '开始答题' }}
      </el-button>

      <!-- 中间标题区域 -->
      <div style="flex: 1; margin: 0 15px;">
        <el-button type="primary" link @click="handleBack" size="small">返回试卷列表</el-button>
        <div
          style="font-size: 16px; font-weight: 500; margin-top: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
          {{ title }}
        </div>
      </div>
    </div>

    <!-- 题型统计 -->
    <div class="stats-bar" v-if="isStart">
      <div class="stats-item">单选题: {{ stats.singleChoice }}道</div>
      <div class="stats-item">多选题: {{ stats.multipleChoice }}道</div>
      <div class="stats-item">填空题: {{ stats.fillBlank }}道</div>
      <div class="stats-item">简答题: {{ stats.essay }}道</div>
    </div>

    <!-- 带阴影的分割线 -->
    <div class="divider"></div>

    <!-- 内容区域 -->
    <div class="content-section">
      <div class="questions-container">
        <el-card style="box-shadow: none; border: none; background: transparent;">
          <!-- 题目列表 -->
          <div v-if="questions.length > 0">
            <div v-for="(question, index) in questions" :key="question.id" class="question-item">
              <!-- 题号和问题 - 内容超出可滚动 -->
              <div class="question-header scrollable-content">
                <span class="question-number">{{ index + 1 }}.</span>
                <span class="question-content">{{ question.content }} ({{ question.score }}分)</span>
              </div>

              <!-- 答案区域 - 根据题型展示不同组件 -->
              <div class="answer-area scrollable-content">
                <!-- 单选题 -->
                <div v-if="question.type === '1'">
                  <el-radio-group v-model="userAnswers[question.id]" class="radio-group">
                    <el-radio v-for="(option, optIndex) in question.options?.split('###')" :key="optIndex"
                      :label="optIndex.toString()" class="radio-option">
                      {{ String.fromCharCode(65 + optIndex) }}. {{ option }}
                    </el-radio>
                  </el-radio-group>
                </div>

                <!-- 多选题 -->
                <div v-if="question.type === '2'">
                  <el-checkbox-group v-model="userAnswers[question.id]" class="checkbox-group">
                    <el-checkbox v-for="(option, optIndex) in question.options?.split('###')" :key="optIndex"
                      :label="optIndex.toString()" class="checkbox-option">
                      {{ String.fromCharCode(65 + optIndex) }}. {{ option }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>

                <!-- 填空题 -->
                <div v-if="question.type === '3'" class="fill-blank">
                  <el-input v-model="userAnswers[question.id]" placeholder="请输入答案" :disabled="!isStart"></el-input>
                </div>

                <!-- 简答题 -->
                <div v-if="question.type === '4'" class="essay-question">
                  <el-input v-model="userAnswers[question.id]" type="textarea" :rows="4" placeholder="请输入答案"
                    :disabled="!isStart"></el-input>
                </div>
              </div>
            </div>
          </div>

          <!-- 无数据状态 -->
          <!-- <div v-else class="empty-state" v-if="isStart">
            <el-empty description="暂无题目数据"></el-empty>
          </div> -->

          <!-- 未开始答题提示 -->
          <div v-else class="not-started">
            <div class="start-prompt">点击"开始答题"按钮开始考试</div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { ExaminaionPaperQuestionForm } from '@/types/examinaion/types';
import { _getExaminaionPaperQuestionInfos } from '@/api/generic/examinaion/examinaion-paper-question-api';
// 假设导入提交答案的API
import { _submitPaper } from '@/api/generic/examinaion/examinaion-paper-api';

// 路由相关
const route = useRoute();
const router = useRouter();

// 响应式数据
const paperId = ref(route.query.id || "");
const title = ref(route.query.title || "");
const isStart = ref(false);
const questions = ref<ExaminaionPaperQuestionForm[]>([]);
// 存储用户答案，使用选项索引而非ABCD
const userAnswers = ref<Record<string, string>>({});

// 题型统计
const stats = computed(() => ({
  singleChoice: questions.value.filter(q => q.type === '1').length,
  multipleChoice: questions.value.filter(q => q.type === '2').length,
  fillBlank: questions.value.filter(q => q.type === '3').length,
  essay: questions.value.filter(q => q.type === '4').length
}));


onMounted(() => {
  // 预加载试卷信息
});

// 开始答题
const start = () => {
  if (!paperId.value) {
    ElMessage.error('获取试卷信息失败');
    return;
  }

  // 获取题目数据
  _getExaminaionPaperQuestionInfos({ id: paperId.value }).then(res => {
    if (res.code == 200 && res.data) {
      questions.value = res.data;
      // 初始化答案对象
      questions.value.forEach(q => {
        if (q.type === '1') {
          userAnswers.value[q.id] = ''; // 单选题初始为空字符串
        } else if (q.type === '2') {
          userAnswers.value[q.id] = []; // 多选题初始为空数组
        } else {
          userAnswers.value[q.id] = ''; // 填空和简答题初始为空
        }
      });
      isStart.value = true;
      ElMessage.success('开始答题');
    } else {
      ElMessage.error('获取题目失败');
    }
  }).catch(err => {
    console.error('获取题目失败', err);
    ElMessage.error('获取题目失败');
  });
};

// 处理交卷数据 - 生成包含问题ID和对应值的List
const prepareSubmitData = () => {
  const submitList: Array<{ examinaionQuestionId: string; answer: string }> = [];

  questions.value.forEach(question => {
    const questionId = question.id;
    const answer = userAnswers.value[questionId];
    let answerValue = '';

    // 根据题型处理答案
    if (question.type === '1') { // 单选题
      if (answer !== '') {
        const options = question.options?.split('###');
        answerValue = options[parseInt(answer)] || '';
      }
    } else if (question.type === '2') { // 多选题
      if (Array.isArray(answer) && answer.length > 0) {
        const options = question.options?.split('###');
        const selectedOptions = answer.map((idx: string) => options[parseInt(idx)]);
        answerValue = selectedOptions.join(';'); // 用分号分隔多个选项
      }
    } else { // 填空和简答题
      answerValue = answer || '';
    }

    submitList.push({
      examinaionQuestionId: questionId as string,
      answer: answerValue as string
    });
  });

  return submitList;
};

// 交卷
const finish = () => {
  // 验证是否完成所有题目
  const unAnswered = questions.value.filter(q => {
    const answer = userAnswers.value[q.id];
    if (q.type === '1') return !answer; // 单选题未作答
    if (q.type === '2') return !answer || answer.length === 0; // 多选题未作答
    return !answer; // 填空和简答题未作答
  });

  // 确认交卷
  ElMessageBox.confirm(
    unAnswered.length > 0
      ? `尚有${unAnswered.length}道题未作答，确定要交卷吗？`
      : '确定要交卷吗？',
    '确认交卷',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      // 准备提交数据
      const submitData = prepareSubmitData();
      console.log('提交的答案数据:', submitData);

      // 实际项目中调用API提交答案
      try {
        const response = await _submitPaper({
          examinaionPaperId: paperId.value as string,
          answers: submitData as [],
        });

        if (response) {
          ElMessage.success('交卷成功');
          setTimeout(() => {
            router.back();
          }, 1000);
        } else {
          ElMessage.error('交卷失败，请重试');
        }
      } catch (error) {
        console.error('交卷失败', error);
        ElMessage.error('交卷失败，请重试');
      }
    })
    .catch(() => {
      // 用户取消操作
    });
};

// 返回
const handleBack = () => {
  if (isStart.value) {
    ElMessageBox.confirm(
      `正在考试中，确定要离开吗？未完成的答案将不被保存`,
      '确认交卷',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
  } else {
    router.back();
  }
};
</script>
<style scoped>
/* 基础样式 */
.stats-bar {
  display: flex;
  flex-wrap: wrap;
  padding: 10px 15px;
  background-color: #f0f7ff;
  border-bottom: 1px solid #e8e8e8;
  gap: 10px 20px;
}

.stats-item {
  font-size: 14px;
  color: #922575;
  display: flex;
  align-items: center;
}

.divider {
  height: 6px;
  background: linear-gradient(90deg, transparent, rgba(0, 0, 0, 0.05), transparent);
}

.content-section {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.questions-container {
  max-width: 1000px;
  margin: 0 auto;
  width: 100%;
  max-height: calc(100vh - 250px); /* 限制最大高度 */
  overflow-y: auto; /* 启用垂直滚动条 */
}

.el-card {
  /* 确保卡片不限制高度 */
  height: auto !important;
  overflow: visible !important;
}

/* 题目样式 */
.question-item {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.03);
}

.question-header {
  max-height: 50vh; /* 限制内容区域高度 */
  overflow-y: auto; /* 启用滚动条 */
  word-break: break-word; /* 确保长文本换行 */
}

.question-number {
  font-weight: bold;
  color: #922575;
  margin-right: 8px;
  min-width: 24px;
}

.question-content {
  flex: 1;
  font-size: 15px;
  color: #333;
}

.answer-area {
  max-height: 50vh; /* 限制内容区域高度 */
  overflow-y: auto; /* 启用滚动条 */
  word-break: break-word; /* 确保长文本换行 */
}

/* 不同题型的样式 */
.radio-group,
.checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.radio-option,
.checkbox-option {
  display: flex;
  align-items: center;
  padding: 5px 0;
}

.fill-blank {
  width: 100%;
  max-width: 500px;
}

.essay-question {
  width: 100%;
}

/* 状态样式 */
.empty-state {
  padding: 50px 0;
  text-align: center;
}

.not-started {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.start-prompt {
  font-size: 16px;
  color: #666;
  padding: 20px 30px;
  border: 1px dashed #ccc;
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-bar {
    padding: 8px 10px;
    gap: 8px 15px;
  }

  .stats-item {
    font-size: 12px;
  }

  .content-section {
    padding: 10px;
  }

  .question-item {
    padding: 12px;
    margin-bottom: 15px;
  }

  .question-header {
    flex-direction: column;
    margin-bottom: 10px;
  }

  .question-number {
    margin-bottom: 5px;
  }

  .answer-area {
    margin-left: 0;
    padding-left: 5px;
  }

  .radio-option,
  .checkbox-option {
    font-size: 14px;
    padding: 4px 0;
  }
}

/* 按钮样式 */
.idoo-details-add {
  background-color: #922575;
  color: white;
}

.idoo-details-finish {
  background-color: #f56c6c;
  color: white;
}
</style>